#!usr/bin/python
# _*_ coding: utf-8 *_*
'''
Created on 29 janv. 2010

@author: paraita
'''


import math
import pickle
import numpy
import matplotlib.pylab as pylab
import Signal
#import scipy.signal.waveforms



def make_sin(a=1, ph=0, freq=440.0, N=100, n=30):
    """
    Create a synthetic 'sine wave' with 
    frequency freq
    N samples
    and n is the number of samples by period >=2
    """
    T = 1.0/freq
    omega = (2*math.pi)/T
    te= T/n       # Sampling period
    print te      
    print 1.0/te  # Sampling frequency
    sig_t = [] 
    sig_s = []
    for i in range(N):
        t = i*te
        sig_t.append(t)
        sig_s.append(a*math.sin((omega*t)+ph))
        
    # Faire un tableau a partir d'une liste    
    x = numpy.array(sig_t)
    y = numpy.array(sig_s)
    return x, y

def make_square(a=2, freq=440.0, r=0.5, N=100, n=30):
    """
    Create a synthetic 'square wave' with 
    frequency freq
    N samples
    and n is the number of samples by period >=2
    
    """
    sig_t = []
    sig_s = []
    
    T = 1.0/freq
    te= T/n       # Sampling period
    
    for i in range(N): 
        t = i*te
        sig_t.append(t)
        if ((i%n)<(n*r)):
            sig_s.append(+a)
        else:
            sig_s.append(-a)
        
    # Faire un tableau a partir d'une liste    
    x = numpy.array(sig_t)
    y = numpy.array(sig_s) 
    return x, y

    
def make_saw(a=1, freq=440.0, N=100, n=30):
    """
    http://en.wikipedia.org/wiki/Sawtooth_wave
    Create a synthetic 'saw wave' with 
    amplitude a
    frequency freq
    N samples
    and n is the number of samples by period >=2
    """
   
    #http://www.scipy.org/Tentative_NumPy_Tutorial
    x = numpy.zeros(N,dtype=numpy.float32)
    y = numpy.zeros(N,dtype=numpy.float32)
    
    T = 1.0/freq
    te= T/n       # Sampling period
    
    for i in range(N): 
        t = i*te
        x[i] = t
        y[i] =  2*a*(t/T - math.floor((t/T)) -0.5)
    return x, y


def make_triangle(a=1, freq=440.0, N=100, n=30):
    """
    #http://en.wikipedia.org/wiki/Triangle_wave
    Create a synthetic 'triangle wave' with 
    amplitude a
    frequency freq
    N samples
    and n is the number of samples by period >=2
    """
    print "Todo !"
    x = numpy.zeros(N,dtype=numpy.float32)
    y = numpy.zeros(N,dtype=numpy.float32)
    
    T = 1.0/freq
    te= T/n       # Sampling period
    
    astuce = make_saw(a, freq, N, n)
    
    for i in range(N): 
        t = i*te
        x[i] = t
        y[i] = math.fabs(astuce[1][i])
    return x, y
    
def add_noise(sig):
    """
    Make signal with gaussian noise
    """
    noise=numpy.random.normal(0,0.1,sig[1].size)  #mean, std dev, num pts
    return sig[0], sig[1]+noise

def save_infile(sig, filename="wave.txt"):
    """
    Write ASCII a signal sig in a given (filename) file
    http://stackoverflow.com/questions/899103/python-write-a-list-to-a-file
    """
    f=open(filename,'w')
    for item in sig[1]:
        f.write("%s\n" % item)
    f.close()
    
def serialize_infile(sig, filename="wave.ser"):
    """
    Serialize a signal sig in a given (filename) file
    """
    f=open(filename,'w')
    pickle.dump(sig, f)
    f.close()
    
#def plot(sig, t, color):
#    pylab.plot(sig[0],sig[1],color, Hold=True)
#    pylab.xlabel('time (s)')
#    pylab.ylabel('voltage (V)')
#    pylab.title(t)
    #pylab.text(60, .025, r'$\mu=100,\ \sigma=15$')
#    pylab.ylim([-1.2, +1.2])
#    pylab.grid(True)
#    pylab.show()
    
    
#s = make_sin()
#s = make_square()
sa = make_saw(a=0.7,N=100)
s = add_noise(sa)
#save_infile(s)
#plot(s,"Saw")

'''
l1 = make_square()
l2 = make_sin()
l3 = make_saw()
pylab.plot(l2[0], l2[1], color='brown', linestyle='', marker='.')
pylab.plot(l1[0], l1[1], 'b.')
pylab.plot(l3[0], l3[1], 'r.')
'''

# je crée les différents signaux
signal1 = Signal.Sinusoide(amplitude=1,phase=0,frequence=440.0, samples=100, n=30)
signal2 = Signal.Square(amplitude=2, r=0.5, frequence=440.0, samples=1000, n=30)
signal3 = Signal.Saw(amplitude=1, frequence=440.0, samples=100, n=30)
signal4 = Signal.Triangle(amplitude=3, frequence=200.0, samples=60, n=50, phase=1.5, offset=-0.0012)

# je récupère leurs valeurs
res1 = signal1.getValues()
res2 = signal2.getValues()
res3 = signal3.getValues()
res4 = signal4.getValues()

# je "plote" ces valeurs
pylab.plot(res1[0], res1[1], color='brown', linestyle='', marker='.')
pylab.plot(res2[0], res2[1], 'b.')
pylab.plot(res3[0], res3[1], 'r.')
pylab.plot(res4[0], res4[1], 'g.')
pylab.ylim([-3, 3])
pylab.xlim([0, 0.009])
pylab.show()
